import {RechargeModel} from "../../../database/models/recharge";

export const typeDefs = `
type Recharge{
  _id: String!
  name: String!
  remarks: String
  RMBCost: Float!
  coin: Int
  freeCoin: Int
  gem: Int
  state: String!
  createAt: String!
  updateAt: String!
}
input RechargeInput{
   _id: String
  name: String!
  remarks: String
  RMBCost: Float!
  coin: Int
  freeCoin: Int
  gem: Int
  state: String!
  createAt: String!
  updateAt: String!
}
`

export const queryDefs = `
   getRechargeItems: [Recharge]!
`

export const mutationDefs = `
  createRechargeItem(recharge: RechargeInput): Recharge
  updateRechargeItem(_id:String!, recharge:RechargeInput): Recharge
  deleteRechargeItem(_id:String!): Boolean
  onRechargeItem(_id:String!): Recharge
  offRechargeItem(_id:String!): Recharge
  `

export const resolvers = {
  Query: {
    getRechargeItems: async (_, {}) => {
      return await RechargeModel.find().sort({state: -1, createAt: 1}).lean()
    },
  },
  Mutation: {
    createRechargeItem: async (_, {recharge}) => {
      const createAt = new Date(recharge.createAt)
      const updateAt = new Date(recharge.updateAt)
      const item = new RechargeModel({...recharge, createAt, updateAt})
      await item.save()
      return item
    },
    updateRechargeItem: async (_, {_id, recharge}) => {
      const updateAt = new Date(recharge.updateAt)
      const item = await RechargeModel.findByIdAndUpdate(_id, {...recharge, updateAt}, {new: true})
      return item
    },
    deleteRechargeItem: async (_, {_id}) => {
      return await RechargeModel.deleteOne({_id})
    },
    onRechargeItem: async (_, {_id}) => {
      const item = await RechargeModel.findById(_id)
      if (item) {
        item.state = 'on'
        await item.save()
        return item
      }
      throw Error('NO_SUCH_RECHARGE_ITEM')
    },
    offRechargeItem: async (_, {_id}) => {
      const item = await RechargeModel.findById(_id)
      if (item) {
        item.state = 'off'
        await item.save()
        return item
      }
      throw Error('NO_SUCH_RECHARGE_ITEM')
    },
  }
}
